<template>
  <div class="user-info-container">
    <!-- 个人信息卡片 -->
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" size="small" @click="handleEdit">
            编辑
          </el-button>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户账号">
          {{ userInfo.useraccount }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ userInfo.username }}
        </el-descriptions-item>
        <el-descriptions-item label="用户角色">
          <el-tag :type="userInfo.role === 'ADMIN' ? 'danger' : 'info'">
            {{ userInfo.role === 'ADMIN' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱地址">
          {{ userInfo.email || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号码">
          {{ userInfo.phone || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="账号状态">
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">
          {{ formatDate(userInfo.createdTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="最后登录时间">
          {{ formatDate(userInfo.lastLoginTime) || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户管理功能（仅管理员可见） -->
    <el-card class="user-list-card" v-if="isAdmin">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button type="danger" @click="goToDeletePage">
              <el-icon><Delete /></el-icon>
              删除管理
            </el-button>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户账号或用户名"
              style="width: 200px; margin-left: 10px; margin-right: 10px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="useraccount" label="用户账号" width="150" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱地址" width="180" />
        <el-table-column prop="phone" label="手机号码" width="120" />
        <el-table-column prop="role" label="用户角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'ADMIN' ? 'danger' : 'info'">
              {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="账号状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginIp" label="最后登录IP" width="120" />
        <el-table-column prop="createdTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 个人信息编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户账号">
          <el-input v-model="editForm.useraccount" disabled />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <!-- 只有管理员才能修改角色和状态 -->
        <el-form-item label="用户角色" prop="role" v-if="isAdmin">
          <el-select v-model="editForm.role" placeholder="请选择用户角色">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        <!-- 普通用户不能修改角色 -->
        <el-form-item label="用户角色" v-else>
          <el-input :value="editForm.role === 'ADMIN' ? '管理员' : '普通用户'" disabled />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <!-- 只有管理员才能修改账号状态 -->
        <el-form-item label="账号状态" prop="status" v-if="isAdmin">
          <el-select v-model="editForm.status" placeholder="请选择账号状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <!-- 普通用户不能修改状态 -->
        <el-form-item label="账号状态" v-else>
          <el-input :value="editForm.status === 1 ? '启用' : '禁用'" disabled />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmitEdit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户列表编辑对话框 -->
    <el-dialog
      v-model="userEditDialogVisible"
      title="编辑用户信息"
      width="500px"
    >
      <el-form
        ref="userEditFormRef"
        :model="userEditForm"
        :rules="userEditRules"
        label-width="80px"
      >
        <el-form-item label="用户账号">
          <el-input v-model="userEditForm.useraccount" disabled />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userEditForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="userEditForm.role" placeholder="请选择用户角色">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="userEditForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userEditForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="userEditForm.status" placeholder="请选择账号状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userEditDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmitUserEdit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo, getUserList, updateUser, deleteUser } from '@/api/user'

export default {
  name: 'UserInfo',
  components: {
    Delete
  },
  setup() {
    const router = useRouter()
    const userInfo = ref({})
    const editDialogVisible = ref(false)
    const loading = ref(false)
    const editFormRef = ref()
    
    const editForm = reactive({
      useraccount: '',
      username: '',
      role: '',
      email: '',
      phone: '',
      status: 1
    })
    
    const editRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      email: [
        { required: false, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: false, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择账号状态', trigger: 'change' }
      ]
    }

    // 用户列表相关
    const userList = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const userEditDialogVisible = ref(false)
    const userEditFormRef = ref()
    
    const userEditForm = reactive({
      id: '',
      useraccount: '',
      username: '',
      role: '',
      email: '',
      phone: '',
      status: 1
    })
    
    const userEditRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      email: [
        { required: false, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: false, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择账号状态', trigger: 'change' }
      ]
    }

    // 计算属性：是否为管理员
    const isAdmin = computed(() => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const user = JSON.parse(userInfoStr)
        return user.role && user.role.toUpperCase() === 'ADMIN'
      }
      return false
    })
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await getUserInfo()
        console.log('个人信息API响应:', response)
        
        // 检查不同的响应结构
        const isSuccess = response?.success || response?.data?.success
        if (isSuccess) {
          // 兼容不同的数据结构
          const userData = response?.data?.data || response?.data || response
          userInfo.value = userData
          console.log('设置的个人信息:', userInfo.value)
        } else {
          console.error('获取个人信息失败:', response)
          ElMessage.error(response?.message || response?.data?.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取个人信息异常:', error)
        ElMessage.error('获取用户信息失败')
      }
    }

    // 获取用户列表（管理员功能）
    const fetchUserList = async () => {
      if (!isAdmin.value) return
      
      loading.value = true
      try {
        const response = await getUserList({
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          keyword: searchKeyword.value
        })
        console.log('用户列表API响应:', response)
        if (response.success) {
          console.log('用户数据:', response.data)
          userList.value = response.data.records || []
          total.value = response.data.total || 0
          console.log('设置的用户列表:', userList.value)
          console.log('设置的总数:', total.value)
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    // 打开编辑对话框
    const handleEdit = () => {
      editForm.useraccount = userInfo.value.useraccount
      editForm.username = userInfo.value.username
      editForm.role = userInfo.value.role
      editForm.email = userInfo.value.email || ''
      editForm.phone = userInfo.value.phone || ''
      editForm.status = userInfo.value.status || 1
      editDialogVisible.value = true
    }

    // 搜索用户
    const handleSearch = () => {
      currentPage.value = 1
      fetchUserList()
    }

    // 重置搜索
    const handleReset = () => {
      searchKeyword.value = ''
      currentPage.value = 1
      fetchUserList()
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchUserList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchUserList()
    }

    // 编辑用户 - 打开编辑对话框
    const handleEditUser = (row) => {
      userEditForm.id = row.id
      userEditForm.useraccount = row.useraccount
      userEditForm.username = row.username
      userEditForm.role = row.role
      userEditForm.email = row.email || ''
      userEditForm.phone = row.phone || ''
      userEditForm.status = row.status || 1
      userEditDialogVisible.value = true
    }

    // 提交用户编辑
    const handleSubmitUserEdit = async () => {
      if (!userEditFormRef.value) return
      
      await userEditFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            console.log('提交用户编辑数据:', {
              id: userEditForm.id,
              username: userEditForm.username,
              role: userEditForm.role,
              email: userEditForm.email,
              phone: userEditForm.phone,
              status: userEditForm.status
            })
            
            const response = await updateUser({
              id: userEditForm.id,
              username: userEditForm.username,
              role: userEditForm.role,
              email: userEditForm.email,
              phone: userEditForm.phone,
              status: userEditForm.status
            })
            
            console.log('编辑用户API响应:', response)
            
            // 检查不同的响应结构
            const isSuccess = response?.success || response?.data?.success
            if (isSuccess) {
              ElMessage.success('更新成功')
              userEditDialogVisible.value = false
              await fetchUserList()
            } else {
              const errorMsg = response?.message || response?.data?.message || '更新失败'
              ElMessage.error(errorMsg)
            }
          } catch (error) {
            console.error('更新用户失败:', error)
            console.error('错误响应:', error.response)
            
            let errorMsg = '更新失败'
            if (error.response?.data?.message) {
              errorMsg = error.response.data.message
            } else if (error.response?.status === 403) {
              errorMsg = '权限不足，需要管理员权限'
            } else if (error.response?.status === 401) {
              errorMsg = '登录已过期，请重新登录'
            } else if (error.message) {
              errorMsg = error.message
            }
            
            ElMessage.error(errorMsg)
          } finally {
            loading.value = false
          }
        } else {
          console.log('表单验证失败')
        }
      })
    }

    // 删除用户
    const handleDeleteUser = (row) => {
      ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        loading.value = true
        try {
          const response = await deleteUser(row.id)
          if (response.success) {
            ElMessage.success('删除成功')
            await fetchUserList()
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          let errorMsg = '删除失败'
          if (error.response?.data?.message) {
            errorMsg = error.response.data.message
          } else if (error.response?.status === 403) {
            errorMsg = '权限不足，需要管理员权限'
          } else if (error.response?.status === 401) {
            errorMsg = '登录已过期，请重新登录'
          }
          ElMessage.error(errorMsg)
        } finally {
          loading.value = false
        }
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      editFormRef.value?.resetFields()
    }
    
    // 跳转到删除管理页面
    const goToDeletePage = () => {
      router.push('/user/delete')
    }
    
    // 提交编辑
    const handleSubmitEdit = async () => {
      if (!editFormRef.value) return
      
      await editFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            // 构建更新数据，普通用户不能修改角色和状态
            const updateData = {
              username: editForm.username,
              email: editForm.email,
              phone: editForm.phone
            }
            
            // 只有管理员才能修改角色和状态
            if (isAdmin.value) {
              updateData.role = editForm.role
              updateData.status = editForm.status
            }
            
            console.log('提交个人信息编辑数据:', updateData)
            
            const response = await updateUserInfo(updateData)
            
            console.log('个人信息编辑API响应:', response)
            
            // 检查不同的响应结构
            const isSuccess = response?.success || response?.data?.success
            if (isSuccess) {
              ElMessage.success('更新成功')
              editDialogVisible.value = false
              await fetchUserInfo()
              // 更新本地存储的用户信息
              const userInfo = localStorage.getItem('userInfo')
              if (userInfo) {
                try {
                  const user = JSON.parse(userInfo)
                  user.username = editForm.username
                  localStorage.setItem('userInfo', JSON.stringify(user))
                } catch (e) {
                  console.error('更新本地用户信息失败:', e)
                }
              }
            } else {
              const errorMsg = response?.message || response?.data?.message || '更新失败'
              ElMessage.error(errorMsg)
            }
          } catch (error) {
            console.error('更新个人信息失败:', error)
            console.error('错误响应:', error.response)
            
            let errorMsg = '更新失败'
            if (error.response?.data?.message) {
              errorMsg = error.response.data.message
            } else if (error.response?.status === 403) {
              errorMsg = '权限不足'
            } else if (error.response?.status === 401) {
              errorMsg = '登录已过期，请重新登录'
            } else if (error.message) {
              errorMsg = error.message
            }
            
            ElMessage.error(errorMsg)
          } finally {
            loading.value = false
          }
        } else {
          console.log('个人信息表单验证失败')
        }
      })
    }
    
    onMounted(() => {
      fetchUserInfo()
      if (isAdmin.value) {
        fetchUserList()
      }
    })
    
    return {
      userInfo,
      editDialogVisible,
      loading,
      editFormRef,
      editForm,
      editRules,
      formatDate,
      handleEdit,
      handleDialogClose,
      handleSubmitEdit,
      // 用户列表相关
      userList,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      isAdmin,
      userEditDialogVisible,
      userEditFormRef,
      userEditForm,
      userEditRules,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleEditUser,
      handleSubmitUserEdit,
      handleDeleteUser,
      goToDeletePage
    }
  }
}
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.user-card {
  max-width: 800px;
  margin: 0 auto;
}

.user-list-card {
  max-width: 1200px;
  margin: 20px auto 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>